package com.lambkit.spring;

import cn.hutool.core.net.NetUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.LinkedHashSet;

/**
 * @author yangyong(孤竹行)
 */
@Component
public class LambkitApplicationStartup implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private Environment env;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        //System.out.println("Please visit url(http://website/lambkit) for runtime details.");
        //ServerContextInfo serverContextInfo = ServiceKit.get(ServerContextInfo.class);
        String msg = "Server running on:\n";
        msg = msg + " > Local:   http://localhost:" + getPort() + getContextPathInfo();
        msg = msg + "\n";
        LinkedHashSet<String> ipList = NetUtil.localIpv4s();
        for(Iterator iterator = ipList.iterator(); iterator.hasNext(); msg = msg + "\n") {
            String ip = (String)iterator.next();
            msg = msg + " > Network: http://" + ip + ":" + getPort() + getContextPathInfo();
        }
        System.out.println(msg);
    }

    private int getPort() {
        return env.getProperty("local.server.port", Integer.class, 8080);
    }

    private String getContextPath() {
        return env.getProperty("server.servlet.context-path", String.class, "");
    }

    private String getContextPathInfo() {
        return "/".equals(getContextPath()) ? "" : getContextPath();
    }
}
